package tum0r.webengine.defaults.command

import tum0r.webengine.annotations.Command
import tum0r.webengine.config.SSLConfig
import tum0r.webengine.enums.ESecurityType
import tum0r.webengine.extension.check
import tum0r.webengine.extension.errorLog
import tum0r.webengine.extension.infoLog
import tum0r.webengine.extension.isExistsFile
import java.io.File

/**
 * 说明: SSL安全设置命令
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/27 20:03
 */
@Command
class SSLCommand {
    /**
     * 设置SSL加密类型
     *
     * @param[type] 加密类型
     */
    fun setSecurityType(type: String) {
        try {
            SSLConfig.SECURITY_TYPE = ESecurityType.valueOf(type)
            "SSL加密类型设置为[${type}]".infoLog()
        } catch (e: Exception) {
            "SSL加密类型设置错误".errorLog()
        }
    }

    /**
     * 验证KeyStore
     *
     * @param[path] KeyStore的文件路径
     * @param[password] KeyStore的密码
     * @param[typeName] 验证的类型
     */
    private fun verifyKeyStore(path: String, password: String, typeName: String): Boolean {
        if (path.check("${typeName}路径") && password.check("${typeName}密码")) {
            val file = File(path)
            if (file.isExistsFile(true)) return true
            else "${typeName}文件不存在".errorLog()
        }
        return false
    }

    /**
     * 设置KeyStore
     *
     * @param[path] KeyStore的文件路径
     * @param[password] KeyStore的密码
     */
    fun setKeyStore(path: String, password: String) {
        if (!verifyKeyStore(path, password, "KeyStore")) return
        SSLConfig.KEY_STORE_FILE = File(path)
        SSLConfig.KEY_STORE_PASSWORD = password.toCharArray()
    }

    /**
     * 设置TrustKeyStore
     *
     * @param[path] TrustKeyStore的文件路径
     * @param[password] TrustKeyStore的密码
     */
    fun setTrustKeyStore(path: String, password: String) {
        if (!verifyKeyStore(path, password, "TrustKeyStore")) return
        SSLConfig.TRUST_KEY_STORE_FILE = File(path)
        SSLConfig.TRUST_KEY_STORE_PASSWORD = password.toCharArray()
    }
}